//
//  LCOAuthController.swift
//  SinaWeiBo
//
//  Created by mac on 16/12/3.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD


//新浪微博对我们的唯一标示
let AppKey = "1963147634"
//授权完成后的回调页
let Redirect_url = "http://www.itcast.cn"
//微博的appSecret
let AppSecret = "3ada504806e8d38441e9347aa814bcc4"

class LCOAuthController: UIViewController {
    
    //把code定义成全局的
//    var code:String?
    //1懒加载webview
    private lazy var webView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        
        setupNaviButton()
        
    }
    //MARK:设置导航栏的按钮
    func setupNaviButton(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(dismissAction))
        navigationItem.title = "微博登录"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(padingAction))
    }
    
    //MARK:设置barbutton的点击事件
    func dismissAction(){
        //解决点击取消按钮后HUD还在旋转的BUG
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: {
        //取消后
        })
    }
    func padingAction(){
        //  执行JavaScript
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com'; document.getElementById('passwd').value = 'guohaibin123'")
        
    }
    
    
    //替换根控制器view为webview
    override func loadView() {
    //MARK: webView的代理方法
        webView.delegate = self
        view = webView
    }
    
    
    //加载数据
    func loadData(){
        //1
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_url)"
        let request = URLRequest(url: URL(string: url)!)
        webView.loadRequest(request)
        
    }
    

}
//MARK:extension扩展功能
extension LCOAuthController: UIWebViewDelegate{
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //MRK:主要WebView将要加载一个请求时调用的方法
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1获取将要加载的url
        guard let urlStr = request.url else{
            return false
        }
        //2判断url的主机地址是否是我们设置的回调页地址
        //  代码执行到此url不为nil
        //  ! 取反不是我们关心的回调页的地址
        
        /*
         1->absoluteString :绝对地址
         2->hasPrefix :前缀
         */
        //判断，如果这个url不是以我们设置的回调页的url开头的就让他加载这个url
        if !urlStr.absoluteString.hasPrefix(Redirect_url) {
            return true
        }
        //执行到这说明url是以我们设置的回调页url开头的，
        //来获取回调页后面code码
        
        //1获取url的？号后面的体
        
        if let query = urlStr.query,query.hasPrefix("code=") {
            let stratIndex = "code=".endIndex
            let code = query.substring(from: stratIndex)
            print(code)
        //调用获取accessToKen的方法

        LCOAuthViewModel.sharedViewModel.getaccessToKen(code: code, callBack: { (isSuccess) in
            if isSuccess{
                //获取用户信息、登录成功
                print("登录成功")
                //释放当前控制器.
                //MARK:注意：切换根视图控制器的通知，必须放到当前控制器dismiss完成以后发送才会有效
                //因为，当前控制器是从别的控制器跳转过来的，必须让当前的控制器完全的dismiss以后，才不会持有当前控制器之前的控制器。
                self.dismiss(animated: false, completion: { 
                    
                })
                //发送通知
                NotificationCenter.default.post(name: NSNotification.Name(notificationName), object: self)
                
            }else{
                //获取信息、登录失败
                print("登录失败")
            }
            
        })
            
        }
        
        //返回值：返回true加载request，返回false不加载request
        return false
    }
    
    
    
    
}
















